﻿using System.IO;
using System.Net;
using System.Text;

namespace EzDesk.Utility.Net
{
    public interface IWebRequestExt
    {
        string GetStringFromUrl(string url);
        string GetStringWithPost(string url,string data);
    }


    public class WebRequestExt : IWebRequestExt
    {
        public WebRequestExt()
        {
        }

        public string GetStringWithPost(string url,string data="")
        {
            var req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = data.Length;
            req.AllowAutoRedirect = true;
            req.CookieContainer = new CookieContainer();
            using(var stream = req.GetRequestStream())
            {
                stream.Write(Encoding.UTF8.GetBytes(data),0,0);
            }

            using (var response = (HttpWebResponse)req.GetResponse())
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    var jsonResult = reader.ReadToEnd();
                    return jsonResult;
                }
            }
        }

        public string GetStringFromUrl(string url)
        {
            var req = (HttpWebRequest)WebRequest.Create(url);
            req.MaximumAutomaticRedirections = 1000;
            req.CookieContainer = new CookieContainer();
            using (var response = (HttpWebResponse)req.GetResponse())
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    var jsonResult = reader.ReadToEnd();
                    return jsonResult;
                }
            }
        }
    }
}
